package javase2.day07;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientDemo {
	public static void main(String[] args) throws IOException{
		ClientDemo client = new ClientDemo();
		client.open("192.168.5.33", 8000);
	}
	public void open(String host, int port) throws IOException{
		//new Socket(host,port) 会发起对host:port的连接
		//如果连接成功返回Socked实例，否则抛出异常
		Socket socket = new Socket(host,port);
		InputStream in = socket.getInputStream();
		OutputStream out = socket.getOutputStream();
		//writer负责从服务器in中读取信息，写入控制台
		new Writer(in,System.out,socket).start();
		//从系统控制台获取信息，发送到服务器
		new Reader(System.in,out,socket).start();
	}
	private class Reader extends Thread{
		InputStream in; 
		OutputStream out;
		Socket s;
		public Reader(InputStream in,OutputStream out,Socket s){
			this.in=in;
			this.out=out;
			this.s=s;
		}
		public void run(){
			Scanner s = new Scanner(in);
			while(true){
				String str = s.nextLine();
				try {
					out.write((str+"\n").getBytes());
					out.flush();
					if(str.equalsIgnoreCase("bye")){
						this.s.close();
						break;
					}
				} catch (IOException e) {
					e.printStackTrace();
					break;
				}
			}
		}
	}
	private class Writer extends Thread{
		InputStream in; 
		PrintStream out;
		Socket s;
		public Writer(InputStream in,PrintStream out,Socket s){
			this.in=in;
			this.out=out;
			this.s=s;
			setDaemon(true);
		}
		public void run(){
			Scanner s = new Scanner(in);
			while(true){
				try {
					String str = s.nextLine();
//					out.write((str+"\n").getBytes());
					out.println(str);
					out.flush();
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					break;
				}
			}
		}
	}
}
